<template>
  <div class="report-details">
    <el-row>
      <el-col :span="24">
        <div class="left">
          <h3 class="title">
            <span>报表名称：</span>
            <span v-show="!isEdit">{{reportName}}</span>
            <i v-show="!isEdit" class="el-icon-edit" @click="isEdit = true"></i>
            <el-input
              clearable
              v-show="isEdit"
              v-model="reportName"
              size="mini"
              placeholder="请输入内容"
              style="width: 300px;"
              @keyup.enter.native="renameReport">
              <el-button
                slot="append"
                size="mini"
                @click.stop="renameReport">
                确定
              </el-button>
            </el-input>
          </h3>
        </div>
        <div class="right">
          <router-link :to="{name: 'NpsReportsOrdersList'}">
            <el-button size="mini">重新筛选数据</el-button>
          </router-link>
        </div>
      </el-col>
    </el-row>
    <el-tabs class="tab" v-model="reportType">
      <el-tab-pane class="panel" label="坐席回访数据统计" name="0">
        <template v-if="reportType === '0'">
          <div class="top">
            <div class="chart-tools">
              <div class="edit" @click.stop="triggerFocus('barChart1', barChartOptions1)">
                <i class="el-icon-edit-outline"></i>
                <!--<div class="icon-tips">编辑图表名称</div>-->
              </div>
              <el-input
                ref="barChart1"
                clearable
                class="chart-name"
                v-show="barChartOptions1.showEditor"
                v-model="barChartOptions1.title.text"
                @keyup.enter.native="renameChart(barChartOptions1, 0)">
                <el-button
                  slot="append"
                  @click="renameChart(barChartOptions1, 0)">
                  确定
                </el-button>
              </el-input>
            </div>
            <ve-histogram
              class="chart"
              :data="tabItem1Chart1Data"
              :dataEmpty="barChartOptions1.dataEmpty"
              :title="barChartOptions1.title"
              :extend="barChartOptions1.extend"
              :settings="barChartOptions1.settings"
              :toolbox="barChartOptions1.toolbox"
              :tooltip="barChartOptions1.tooltip"
              :legend="barChartOptions1.legend"
              :yAxis="barChartOptions1.yAxis"
              :backgroundColor="barChartOptions1.bgColor">
            </ve-histogram>
          </div>
          <div class="bottom">
            <div class="chart-tools">
              <div class="edit" @click.stop="triggerFocus('barChart2', barChartOptions2)">
                <i class="el-icon-edit-outline"></i>
                <!--<div class="icon-tips">编辑图表名称</div>-->
              </div>
              <el-input
                ref="barChart2"
                clearable
                class="chart-name"
                v-show="barChartOptions2.showEditor"
                v-model="barChartOptions2.title.text"
                @keyup.enter.native="renameChart(barChartOptions2, 1)">
                <el-button
                  slot="append"
                  @click.stop="renameChart(barChartOptions2, 1)">
                  确定
                </el-button>
              </el-input>
            </div>
            <ve-histogram
              class="chart"
              :data="tabItem1Chart2Data"
              :dataEmpty="barChartOptions2.dataEmpty"
              :title="barChartOptions2.title"
              :extend="barChartOptions2.extend"
              :settings="barChartOptions2.settings"
              :toolbox="barChartOptions2.toolbox"
              :tooltip="barChartOptions2.tooltip"
              :legend="barChartOptions2.legend"
              :yAxis="barChartOptions2.yAxis"
              :backgroundColor="barChartOptions2.bgColor">
            </ve-histogram>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane class="panel" label="NPS数据" name="1">
        <template v-if="reportType === '1'">
          <div class="top">
            <div class="chart-tools">
              <div class="edit" @click.stop="triggerFocus('pieChart1', pieChartOptions1)">
                <i class="el-icon-edit-outline"></i>
                <!--<div class="icon-tips">编辑图表名称</div>-->
              </div>
              <el-input
                ref="pieChart1"
                clearable
                class="chart-name"
                v-show="pieChartOptions1.showEditor"
                v-model="pieChartOptions1.title.text"
                @keyup.enter.native="renameChart(pieChartOptions1, 0)">
                <el-button
                  slot="append"
                  @click.stop="renameChart(pieChartOptions1, 0)">
                  确定
                </el-button>
              </el-input>
            </div>
            <ve-pie
              class="chart"
              :data="tabItem2Chart1Data"
              :dataEmpty="pieChartOptions1.dataEmpty"
              :title="pieChartOptions1.title"
              :legend="pieChartOptions1.legend"
              :extend="pieChartOptions1.extend"
              :toolbox="pieChartOptions1.toolbox">
            </ve-pie>
          </div>
          <div class="bottom">
            <div class="chart-tools">
              <div class="edit" @click.stop="triggerFocus('barChart3', barChartOptions3)">
                <i class="el-icon-edit-outline"></i>
                <!--<div class="icon-tips">编辑图表名称</div>-->
              </div>
              <el-input
                ref="barChart3"
                clearable
                class="chart-name"
                v-show="barChartOptions3.showEditor"
                v-model="barChartOptions3.title.text"
                @keyup.enter.native="renameChart(barChartOptions3, 1)">
                <el-button
                  slot="append"
                  @click.stop="renameChart(barChartOptions3, 1)">
                  确定
                </el-button>
              </el-input>
            </div>
            <ve-histogram
              class="chart"
              :data="tabItem2Chart2Data"
              :dataEmpty="barChartOptions3.dataEmpty"
              :title="barChartOptions3.title"
              :extend="barChartOptions3.extend"
              :settings="barChartOptions3.settings"
              :toolbox="barChartOptions3.toolbox"
              :tooltip="barChartOptions3.tooltip"
              :legend="barChartOptions3.legend"
              :yAxis="barChartOptions3.yAxis"
              :backgroundColor="barChartOptions3.bgColor">
            </ve-histogram>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane class="panel" label="失分情况统计" name="2">
        <template v-if="reportType === '2'">
          <div class="container">
            <div class="top" v-show="table1Options.show">
              <div class="toolsbar clearfix">
                <div class="right">
                  <div class="inline-block">
                    <i class="el-icon-edit-outline" @click.stop="triggerFocus('table1', table1Options)"></i>
                  </div>
                  <div class="inline-block">
                    <a :href="getDownloadUrl(table1Options.title.text, 0)" download>
                      <i class="el-icon-download"></i>
                    </a>
                  </div>
                </div>
                <el-input
                  ref="table1"
                  clearable
                  class="chart-name"
                  v-show="table1Options.showEditor"
                  v-model="table1Options.title.text"
                  @keyup.enter.native="renameChart(table1Options, 0)">
                  <el-button
                    slot="append"
                    @click.stop="renameChart(table1Options, 0)">
                    确定
                  </el-button>
                </el-input>
              </div>
              <h3 class="tablename">{{table1Options.title.text}}</h3>
              <table class="dynamic-table">
                <tbody v-html="createTabItem3Table1()"></tbody>
              </table>
            </div>
            <p class="data-empty" v-show="!table1Options.show">暂无数据</p>
          </div>
          <div class="container">
            <div class="bottom" v-show="table2Options.show">
              <div class="toolsbar clearfix">
                <div class="right">
                  <div class="inline-block">
                    <i class="el-icon-edit-outline" @click.stop="triggerFocus('table2', table2Options)"></i>
                  </div>
                  <div class="inline-block">
                    <a :href="getDownloadUrl(table2Options.title.text, 1)" download>
                      <i class="el-icon-download"></i>
                    </a>
                  </div>
                </div>
                <el-input
                  ref="table2"
                  clearable
                  class="chart-name"
                  v-show="table2Options.showEditor"
                  v-model="table2Options.title.text"
                  @keyup.enter.native="renameChart(table2Options, 1)">
                  <el-button
                    slot="append"
                    @click.stop="renameChart(table2Options, 1)">
                    确定
                  </el-button>
                </el-input>
              </div>
              <h3 class="tablename">{{table2Options.title.text}}</h3>
              <table class="dynamic-table">
                <thead>
                <tr>
                  <th>评分大类</th>
                  <th>推荐者</th>
                  <th>被动者</th>
                  <th>贬损者</th>
                  <th>总计</th>
                  <th>NPS值</th>
                  <th>失分结构</th>
                  <th>失分原因</th>
                  <th>数量</th>
                  <th>占比</th>
                </tr>
                </thead>
                <tbody v-html="createTabItem3Table2()"></tbody>
              </table>
            </div>
            <p class="data-empty" v-show="!table2Options.show">暂无数据</p>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane class="panel" label="月度处罚统计" name="3">
        <template v-if="reportType === '3'">
          <div class="container">
            <div class="top" v-show="table3Options.show">
              <div class="toolsbar clearfix">
                <div class="right">
                  <div class="inline-block">
                    <i class="el-icon-edit-outline" @click.stop="triggerFocus('table3', table3Options)"></i>
                  </div>
                  <div class="inline-block">
                    <a :href="getDownloadUrl(table3Options.title.text, 0)" download>
                      <i class="el-icon-download"></i>
                    </a>
                  </div>
                </div>
                <el-input
                  ref="table3"
                  clearable
                  class="chart-name"
                  v-show="table3Options.showEditor"
                  v-model="table3Options.title.text"
                  @keyup.enter.native="renameChart(table3Options, 0)">
                  <el-button
                    slot="append"
                    @click.stop="renameChart(table3Options, 0)">
                    确定
                  </el-button>
                </el-input>
              </div>
              <h3 class="tablename">{{table3Options.title.text}}</h3>
              <table class="dynamic-table table3">
                <thead>
                <tr>
                  <th>分公司</th>
                  <th>NPS值</th>
                  <th>分公司贬损者数量</th>
                  <th>分公司总经理罚金</th>
                  <th>分公司市场主管罚金</th>
                  <th>分部</th>
                  <th>分部贬损者数量</th>
                  <th>分部经理罚金</th>
                  <th>店铺</th>
                  <th>店铺贬损者数量</th>
                  <th>销售代表罚金</th>
                  <th>合计罚金</th>
                </tr>
                </thead>
                <tbody v-html="createTableBody()"></tbody>
              </table>
            </div>
            <p class="data-empty" v-show="!table3Options.show">暂无数据</p>
          </div>
        </template>
      </el-tab-pane>
      <div class="tab-mask" v-show="tabLoading">
        <div class="err" v-if="getDataErr">
          <span @click="getReportDetails">数据加载错误，点我重新加载！</span>
        </div>
        <div class="ok" v-else>
          <i class="el-icon-loading"></i>
          <p>数据加载中...</p>
        </div>

      </div>
    </el-tabs>
  </div>
</template>

<script>

  import env from '@/config/env'
  import {
    getNpsReportDetails,
    renameNpsReport,
    renameNpsReportChart,
    npsReportChartDownload
  } from "@/service/getData";

  const barChartOptions = (labelMap) => ({
    extend: {
      'xAxis.0.axisLabel.rotate': 0,
      series: {
        title: 'NPS值',
        type: 'bar',
        barWidth: '30%',
        label: {
          normal: {
            show: true,
            position: "top",
            formatter: '{c}%',
            fontSize: 12,
            color: '#222',
          }
        },
        itemStyle: {
          normal: {
            color: '#3398db'
          }
        }
      }
    },
    settings: {
      labelMap: labelMap,
    },
    title: {
      top: '0',
      text: 'faefew',
      left: 'center',
      textStyle: {
        fontSize: '24',
        fontWeight: '100',
        color: '#222',
      }
    },
    legend: {
      bottom: 20
    },
    yAxis: {
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      },
      axisTick: {
        show: false,
      },
    },
    toolbox: {
      right: 30,
      feature: {
        magicType: {
          type: [],
        },
        saveAsImage: {
          title: ' '  // 这里需要为空格，不能是空字符串
        },
      }
    },
    tooltip: {
      formatter: '{b}<br>{a}: {c}%'
    },
    showEditor: false,
    dataEmpty: false
  })

  const pieChartOptions = () => ({
    title: {
      top: '0',
      text: 'faefew',
      left: 'center',
      textStyle: {
        fontSize: '24',
        fontWeight: '100',
        color: '#222',
      }
    },
    extend: {
      series: {
        label: {
          normal: {
            show: true,
            formatter: '{b}: {c}%',
          }
        },
      }
    },
    legend: {
      bottom: 30
    },
    toolbox: {
      right: 30,
      feature: {
        magicType: {
          type: [],
        },
        saveAsImage: {
          title: ' '
        },
      }
    },
    showEditor: false,
    dataEmpty: false
  })

  const tableOptions = () => ({
    show: false,
    title: {
      text: ''
    },
    showEditor: false
  })

  export default {
    data() {
      return {
        forCount: 0,
        reportName: '',
        isEdit: false,
        reportType: '0',
        tabLoading: false,
        getDataErr: false,
        responseData: {},
        barChartTitle1: '',
        barChartTitle2: '',
        barChartTitle3: '',
        pieChartTitle1: '',
        barChartOptions1: barChartOptions({
          'percentage': '接通率'
        }),
        barChartOptions2: barChartOptions({
          'percentage': '错误率'
        }),
        barChartOptions3: barChartOptions({
          'percentage': 'NPS值'
        }),
        table1Options: tableOptions(),
        table2Options: tableOptions(),
        table3Options: tableOptions(),
        pieChartOptions1: pieChartOptions(),
        chartTitleInputFocusTimer: null
      }
    },
    computed: {
      reportId() {
        return this.$route.params.id
      },
      tabData() {
        const data = this.responseData || {}
        let target = {
          chart1: [],
          chart2: []
        }
        const setData = (field1, field2) => {
          field2 = field2 || field1
          const data0 = data[field1] || {}
          const data1 = data[field2] || {}
          target.chart1 = data0['0'] || []
          target.chart2 = data1['1'] || []
        }
        switch (this.reportType) {
          case '0':
            setData('callBackDataStatisticsDtos')
            break
          case '1':
            setData('npsDataUserClassifyStatisticsDtos', 'branchCompanyNpsValueStatisticsDtos')
            break
          case '2':
            setData('lastThreeBranchesLoseScoreStatisticsDtos', 'scoreCategoriesLoseScoreStatisticsDtos')
            break
          case '3':
            setData('monthlyPunishmentStatisticsDtos')
            break
        }
        return target
      },
      tabItem1Chart1Data() {
        if (this.reportType !== '0') {
          return {columns: [], rows: []}
        }
        const data = this.tabData.chart1
        const chartData = this.formatChartData(data)
        this.changeChartOptions(this.barChartOptions1, data, chartData, true)
        return chartData
      },
      tabItem1Chart2Data() {
        if (this.reportType !== '0') {
          return {columns: [], rows: []}
        }
        const data = this.tabData.chart2
        const chartData = this.formatChartData(data)
        this.changeChartOptions(this.barChartOptions2, data, chartData, true)
        return chartData
      },
      tabItem2Chart1Data() {
        let chartData = {
          columns: [],
          rows: []
        }
        if (this.reportType !== '1') {
          return chartData
        }
        const items = ['贬损者', '被动者', '推荐者']
        const data = this.tabData.chart1
        chartData.columns = ['classify', 'percentage']
        chartData.rows = data.map(item => ({
          classify: items[item.classify],
          percentage: parseFloat(item.percentage)
        }))
        this.changeChartOptions(this.pieChartOptions1, data, chartData, false)
        return chartData
      },
      tabItem2Chart2Data() {
        if (this.reportType !== '1') {
          return {columns: [], rows: []}
        }
        const data = this.tabData.chart2
        const chartData = this.formatChartData(data)
        this.changeChartOptions(this.barChartOptions3, data, chartData, true)
        return chartData
      },
      tabItem3Table1Data() {
        if (this.reportType !== '2') {
          return []
        }
        const data = this.tabData.chart1
        this.changeTableOptions(this.table1Options, data)
        return data
      },
      tabItem3Table2Data() {
        if (this.reportType !== '2') {
          return []
        }
        const data = this.tabData.chart2
        this.changeTableOptions(this.table2Options, data)
        return data
        // // 添加合计行数据
        // const add = (a, b, isPercent = false) => {
        //   let val = parseFloat(a) + parseFloat(b)
        //   return isPercent ? val.toFixed(2) + '%' : val
        // }
        // const subSum = (array) => array.reduce((acc, item) => {
        //   return {
        //     loseScoreReson: '--',
        //     loseScoreResonNum: add(acc.loseScoreResonNum, item.loseScoreResonNum),
        //     // percentage: add(acc.percentage, item.percentage, true)
        //     percentage: '100.00%'
        //   }
        // }, {loseScoreResonNum: 0, percentage: 0})
        // const subtotalList = data.map(item => {
        //   const reasons = item.scoreCategoriesLoseScoreModels || []
        //   return subSum(reasons)
        // })
        // const subtotal = subSum(subtotalList)
        // const initValue = {
        //   presenterNum: 0,
        //   passivesNum: 0,
        //   detractorsNum: 0,
        //   totalNum: 0,
        //   npsValue: 0,
        //   loseScoreStructure: 0
        // }
        // const total = data.reduce((acc, item) => {
        //   return {
        //     presenterNum: add(acc.presenterNum, item.presenterNum),
        //     passivesNum: add(acc.passivesNum, item.passivesNum),
        //     detractorsNum: add(acc.detractorsNum, item.detractorsNum),
        //     totalNum: add(acc.totalNum, item.totalNum),
        //     // npsValue: add(acc.npsValue, item.npsValue, true),
        //     npsValue: '100.00%',
        //     // loseScoreStructure: add(acc.loseScoreStructure, item.loseScoreStructure, true)
        //     loseScoreStructure: '100.00%'
        //   }
        // }, initValue)
        // total.scoreCategories = '合计'
        // total.scoreCategoriesLoseScoreModels = [subtotal]
        // return data.length ? data.concat(total) : []
      },
      tabItem4Table1Data() {
        if (this.reportType !== '3') {
          return []
        }
        const data = this.tabData.chart1
        this.changeTableOptions(this.table3Options, data)
        return data
      },
    },
    methods: {

      // 图表下载接口
      getDownloadUrl(fileName, tableLocal) {
        const query = {
          id: this.reportId,
          reportType: this.reportType,
          reportName: fileName,
          tableLocal: tableLocal,
          UBToken: localStorage.getItem('UBToken')
        }
        let params = []
        for (let key in query) {
          query.hasOwnProperty(key) && params.push(`${key}=${encodeURIComponent(query[key])}`)
        }
        const baseUrl = env.baseUrl3
        const url = '/nps/nps/report/download?' + params.join('&')
        return baseUrl + url
      },

      // 获取图表数据
      getReportDetails() {
        this.tabLoading = true
        getNpsReportDetails({
          id: this.$route.params.id,
          reportType: this.reportType
        }).then(res => {
          this.responseData = res.data.data || {}
          this.getDataErr = false
          this.tabLoading = false
          this.reportName = this.responseData.reportName
        }).catch(err => {
          this.getDataErr = true
        })
      },

      // 修改图表配置
      changeChartOptions(options, data, formatData, isBarChart) {
        const title = data[0] ? data[0].tableName : ''
        options.title.text = title
        options.dataEmpty = !formatData.rows.length
        if (isBarChart) {
          options.extend['xAxis.0.axisLabel.rotate'] = formatData.rows.length >= 10 ? 45 : 0
        }
      },

      // 修改表格配置
      changeTableOptions(options, data) {
        if (!data.length) {
          return
        }
        options.show = true
        options.title.text = data[0].tableName
      },

      // 重命名报表
      renameReport() {
        renameNpsReport({
          id: this.reportId,
          reportName: this.reportName
        }).then(res => {
          this.$message.success('修改成功！')
        }).catch(err => {
          this.$message.error('修改失败！')
        }).finally(() => {
          this.isEdit = false
        })
      },

      // 重命名图表标题
      renameChart(options, tableLocal) {
        options.loading = true
        renameNpsReportChart({
          id: this.reportId,
          reportType: this.reportType,
          tableLocal: tableLocal,
          tableName: options.title.text
        }).then(res => {
          this.$message.success('修改成功！')
        }).catch(err => {
          this.$message.error('修改失败！')
        }).finally(() => {
          options.showEditor = false
          options.loading = false
        })
      },

      // 创建失分情况统计 - 后三分公司失分原因及数量表
      createTabItem3Table1() {
        return this.tabItem3Table1Data.map(item => {
          const fields = ['loseScoreReson', 'loseScoreResonNum', 'percentage']
          let reasons = item.scoreCategoriesLoseScoreModels
          reasons = this.isEmpty(reasons) ? this.createEmptyLoseScoreReason() : reasons
          const totalInitVal = {
            loseScoreResonNum: 0,
            percentage: 0
          }
          const total = reasons.reduce((acc, item) => ({
            loseScoreReson: '合计',
            loseScoreResonNum: parseFloat(acc.loseScoreResonNum) + parseFloat(item.loseScoreResonNum),
            // percentage: (parseFloat(acc.percentage) + parseFloat(item.percentage)).toFixed(2) + '%',
            percentage: '100.00%',
          }), totalInitVal)

          const list = reasons.concat(total)
          const length = list.length
          const rowspan = length + 1  // 加合计行

          const otherRows = list.map((row, index) => {
            const columns = fields.map(field => `<td>${this.formatCellValue(row[field], field)}</td>`).join('')
            const rows = (index === length - 1) ? `<tr class="total">${columns}</tr>` : `<tr>${columns}</tr>`
            return rows
          }).join('')

          const thead = '<th>失分原因</th><th>数量</th><th>占比</th>'
          const branchCompany = this.formatCellValue(item.branchCompany, 'branchCompany')
          const firstRows = `<tr><td rowspan="${rowspan}">${branchCompany}</td>${thead}</tr>`
          return firstRows + otherRows

        }).join('')
      },

      // 创建失分情况统计 - 各评分大类失分结构原因数量统计表
      createTabItem3Table2() {
        const categories = ['其他', '卖场', '安装', '送货', '品牌', '服务', '产品']
        const tbFields = [
          'scoreCategories',
          'presenterNum',
          'passivesNum',
          'detractorsNum',
          'totalNum',
          'npsValue',
          'loseScoreStructure'
        ]
        const data = this.tabItem3Table2Data
        const lastRow = data.length - 1
        let rowspan = 1
        return data.map((item, index) => {
          const fields = ['loseScoreReson', 'loseScoreResonNum', 'percentage']
          let emptyReason = this.createEmptyLoseScoreReason()
          if(index === lastRow) {
            emptyReason[0].loseScoreResonNum = item.loseScoreResonNum
            emptyReason[0].percentage = item.percentage
          }
          let reasons = item.scoreCategoriesLoseScoreModels
          reasons = this.isEmpty(reasons) ? emptyReason : reasons
          rowspan = reasons.length

          const otherRows = reasons.map((row, index) => {
            const columns = fields.map(field => `<td>${this.formatCellValue(row[field], field)}</td>`).join('')
            return index === 0 ? columns : `<tr>${columns}</tr>`
          })

          const firstRowsTds = tbFields.map(field => {
            const val = item[field]
            if (field === 'scoreCategories') {
              const text = val === '合计' ? val : categories[val]
              return `<td rowspan="${rowspan}">${this.formatCellValue(text, field)}</td>`
            }
            return `<td rowspan="${rowspan}">${this.formatCellValue(val, field)}</td>`
          }).join('') + otherRows.shift()

          const firstRows = index === lastRow ? `<tr class="total">${firstRowsTds}</tr>` : `<tr>${firstRowsTds}</tr>`
          return [firstRows].concat(otherRows).join('')

        }).join('')
      },

      // 创建月度处罚统计表分公司级单元格
      createTableBody() {
        const fields = [
          'branchCompany',
          'npsValue',
          'branchCompanyDetractorsNum',
          'branchCompanyManagerForfeit',
          'branchCompanyMarketerForfeit',
          'monthlyPunishmentDepartmentModels',
          'totalForfeit'
        ]
        return this.tabItem4Table1Data.map(item => {
          let departments = item.monthlyPunishmentDepartmentModels
          departments = this.isEmpty(departments) ? this.createEmptyDepartment() : departments

          const shopsNumList = departments.map(department => {
            let shops = department.monthlyPunishmentShopModels
            shops = this.isEmpty(shops) ? this.createEmptyShop() : shops
            return shops.length
          })

          const rowspan = shopsNumList.reduce((acc, item) => acc + item, 0)
          let departmentRows = this.createDepartmentTableCell(departments)

          const columns = fields.map(field => {
            if (field === 'monthlyPunishmentDepartmentModels') {
              return departmentRows.shift()
            }
            return `<td rowspan="${rowspan}">${this.formatCellValue(item[field], field)}</td>`
          }).join('')

          return `<tr>${columns}</tr>` + departmentRows.join('')
        }).join('')
      },

      // 创建月度处罚统计表分部级单元格
      createDepartmentTableCell(data) {
        const fields = ['branchDepartment', 'branchDepartmentDetractorsNum', 'branchDepartmentManagerForfeit']
        let firstRow = []
        const rows = data.map((item, index) => {
          let shops = item.monthlyPunishmentShopModels
          shops = this.isEmpty(shops) ? this.createEmptyShop() : shops
          const rowspan = shops.length

          let shopRows = this.createShopTableCell(shops)
          let columns = fields.map(field => `<td rowspan="${rowspan}">${this.formatCellValue(item[field], field)}</td>`).join('')
          columns += shopRows.shift()
          if (index === 0) {
            firstRow = shopRows
            return columns
          }
          return `<tr>${columns}</tr>` + shopRows.join('')
        })

        const result = [rows.shift()].concat(firstRow.concat(rows).join(''))
        return result
      },

      // 创建月度处罚统计表店铺级单元格
      createShopTableCell(data) {
        const fields = ['shopName', 'shopDetractorsNum', 'saleRepForfeit']
        let rows = data.map((item, index) => {
          const columns = fields.map(field => `<td>${this.formatCellValue(item[field], field)}</td>`).join('')
          return index === 0 ? columns : `<tr>${columns}</tr>`
        });
        const result = [rows.shift()].concat(rows.join(''))
        return result
      },

      // 创建空分部
      createEmptyDepartment() {
        return [{
          "branchDepartment": "",
          "branchDepartmentDetractorsNum": "",
          "branchDepartmentManagerForfeit": "",
          "monthlyPunishmentShopModels": this.createEmptyShop()
        }]
      },

      // 创建空店铺
      createEmptyShop() {
        return [{
          "shopName": "",
          "shopDetractorsNum": "",
          "saleRepForfeit": ""
        }]
      },

      // 创建空失分原因
      createEmptyLoseScoreReason() {
        return [{
          "loseScoreReson": "",
          "loseScoreResonNum": "",
          "percentage": ""
        }]
      },

      // 空数据
      isEmpty(data) {
        return !(Array.isArray(data) && data.length)
      },

      // 格式化单元格的值
      formatCellValue(value, field) {
        const fields = ['scoreCategories', 'loseScoreReson', 'branchCompany', 'branchDepartment', 'shopName']
        if(value !== 0 && !value) {
          return fields.indexOf(field) > -1 ? '--' : 0
        }
        return value
      },

      // 格式化图表数据格式
      formatChartData(data, columns = ['branchCompany', 'percentage']) {
        const rows = data.map(row => {
          let obj = {}
          columns.forEach(column => {
            const val = parseFloat(row[column])
            obj[column] = isNaN(val) ? row[column] : val
          })
          return obj
        })
        return {columns, rows}
      },

      // 输入框获取焦点
      triggerFocus(ref, options) {
        options.showEditor = true
        const input = this.$refs[ref].$el.querySelector('input')
        clearTimeout(this.chartTitleInputFocusTimer)
        this.chartTitleInputFocusTimer = setTimeout(() => {
          input.focus()
        }, 0)
      },

    },
    watch: {
      reportType: {
        immediate: true,
        handler: function () {
          const options = [
            this.barChartOptions1,
            this.barChartOptions2,
            this.barChartOptions3,
            this.pieChartOptions1
          ]
          options.forEach(item => {
            item.showEditor = false
          })
          this.getReportDetails()
        }
      },
    }
  }
</script>

<style lang="scss">


  .report-details {
    .top, .bottom {
      position: relative;
      .chart-name {
        position: absolute;
        top: -10px;
        left: 0;
        z-index: 5;
        text-align: center;
        font-size: 16px;
        padding: 10px;
        /*display: block;*/
        /*width: 100%;*/
        box-sizing: border-box;
        background-color: #fff;
        input {
          text-align: center;
        }
      }
      .edit {
        position: absolute;
        top: 4px;
        right: 60px;
        z-index: 4;
        font-size: 18px;
        cursor: pointer;
        &:hover {
          color: #3b97d7;
          .icon-tips {
            display: block;
          }
        }
        .icon-tips {
          position: absolute;
          bottom: -15px;
          left: 50%;
          display: none;
          font-size: 12px;
          color: #3b97d7;
          white-space: nowrap;
          transform: translateX(-50%);
        }
      }
      .toolsbar {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        padding: 30px 0;
        .inline-block {
          position: relative;
          margin-left: 5px;
          i {
            font-size: 18px;
            cursor: pointer;
            line-height: 40px;
            &:hover {
              color: #409eff;
            }
          }
          span {
            position: absolute;
            bottom: -15px;
            left: 50%;
            white-space: nowrap;
            transform: translateX(-50%);
          }
        }
        .chart-name {
          top: 0;
          padding: 30px 0;
          background-color: #fff;
        }
        a {
          color: #5e6b7c;
        }
      }
    }
    .dynamic-table {
      table-layout: fixed;
      width: 100%;
      border-collapse: collapse;
      th, td {
        border: 1px solid #999;
        padding: 10px;
        text-align: center;
      }
      th {
        background-color: #eef1f6;
      }
      .total td {
        font-weight: bold;
        /*background-color: #eee;*/
      }
      &.table3 {
        tr:last-child td {
          font-weight: bold;
        }
      }
    }
    .v-charts-data-empty {
      z-index: 10;
      background-color: #fff;
    }
  }

  .clearfix:after {
    content: '';
    display: block;
    height: 0;
    visibility: hidden;
    clear: both;
  }

  .left {
    float: left;
  }

  .right {
    float: right;
  }

  .inline-block {
    display: inline-block;
  }

  .title {
    font-weight: 500;
    font-size: 18px;
    color: #222;
  }

  .el-icon-edit {
    display: inline-block;
    padding: 0 10px;
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
  }

  .tab {
    margin-top: 30px;
  }

  .panel {
    /*min-height: 100px;*/
    overflow: hidden;
    .top {
      position: relative;
      margin-top: 50px;
      /*margin: 50px 0;*/
    }
    .bottom {
      position: relative;
      margin-top: 50px;
    }
    .chart-name {
      position: absolute;
      top: 0;
      left: 0;
    }
  }

  .tablename {
    height: 40px;
    padding: 30px 0;
    font-size: 24px;
    font-weight: 500;
    text-align: center;
    line-height: 40px;
  }

  .container {
    position: relative;
    min-height: 200px;
    background-color: #fff;
    .data-empty {
      position: absolute;
      top: 50%;
      left: 50%;
      font-size: 14px;
      color: #888;
      transform: translate(-50%, -50%);
    }
  }

  .chart-tools {
    position: relative;
  }

  .tab-mask {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    text-align: center;
    background-color: #fff;

    .el-icon-loading {
      display: inline-block;
      font-size: 24px;
      margin: 0 auto;
    }

    .err span {
      display: inline-block;
      padding: 5px 10px;
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }

  }


</style>
